package com.cr.crandroid.ui.person.car;


import android.content.DialogInterface;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.cr.crandroid.R;
import com.cr.crandroid.adapter.CarAdapter;
import com.cr.crandroid.bean.Car;
import com.cr.crandroid.ui.person.user.LoginViewModel;
import com.cr.crandroid.utils.CommonConstant;
import com.cr.crandroid.utils.OConvertUtils;
import com.cr.crandroid.utils.OkHttpManager;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.snackbar.Snackbar;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class CarFragment extends Fragment {
    private CarAdapter carAdapter;
    private List<Car> cars = new ArrayList<>();
    private Car car = new Car();
    private Integer carIndex;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_car, container, false);
        carAdapter = new CarAdapter(null);
        RecyclerView recyclerView = root.findViewById(R.id.recyclerView);
        recyclerView.setAdapter(carAdapter);
        View emptyCar = inflater.inflate(R.layout.empty_car, container, false);
        carAdapter.setEmptyView(emptyCar);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        Button button = root.findViewById(R.id.button);
        button.setOnClickListener(view -> {
            Navigation.findNavController(view).navigate(R.id.action_carFragment_to_addCarFragment);
        });
        carAdapter.setOnItemClickListener((adapter, view, position) -> {
            Bundle bundle = new Bundle();
            car = carAdapter.getData().get(position);
            updateCar(car);
        });
        String[] checkArray = new String[]{"详情", "删除"};
        MaterialAlertDialogBuilder materialAlertDialog = new MaterialAlertDialogBuilder(getContext())
                .setItems(checkArray, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch (i) {
                            case 0:
                                updateCar(car);
                                break;
                            case 1:
                                deleteCar();
                                break;

                        }

                    }
                });

        carAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                car = carAdapter.getData().get(position);
                carIndex = position;
                materialAlertDialog.show();
                return false;
            }
        });
        getCarsList();
        return root;
    }

    private void updateCar(Car car) {
        Bundle bundle = new Bundle();
        bundle.putString("car", new Gson().toJson(car, Car.class));
        Navigation.findNavController(getView()).navigate(R.id.action_carFragment_to_addCarFragment, bundle);
    }

    private void deleteCar() {
        MaterialAlertDialogBuilder materialAlertDialog = new MaterialAlertDialogBuilder(getContext())
                .setTitle("是否删除");

        materialAlertDialog.setNegativeButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Map<String, String> map = new HashMap<>();
                        map.put("id", OConvertUtils.getString(car.getId()));
                        OkHttpManager.delete(CommonConstant.URL + "/car/delete", map, new Callback() {
                            @Override
                            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                                String res = response.body().string();
                                JsonObject result = JsonParser.parseString(res).getAsJsonObject();
                                if (Integer.parseInt(String.valueOf(result.get("code"))) != CommonConstant.ERROR) {
                                    if (result.get("result") != null) {
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Snackbar.make(getView(), OConvertUtils.getString(result.get("message").toString()),
                                                        Snackbar.LENGTH_LONG).show();
                                                carAdapter.removeAt(carIndex);
                                            }
                                        });
                                    }
                                }
                            }

                            @Override
                            public void onFailure(@NonNull Call call, @NonNull IOException e) {

                            }
                        });


                    }
                }).start();
            }
        });
        materialAlertDialog.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                return;
            }
        });
        materialAlertDialog.show();
    }


    private void getCarsList() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> map = new HashMap<>();
                map.put("userId", OConvertUtils.getString(LoginViewModel.user.get("id").toString()));
                OkHttpManager.get(CommonConstant.URL + "/car/queryPersonCar", map, new Callback() {
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String res = response.body().string();
                        JsonObject result = JsonParser.parseString(res).getAsJsonObject();
                        if (Integer.parseInt(String.valueOf(result.get("code"))) != CommonConstant.ERROR) {
                            if (result.get("result") != null) {
                                cars = new Gson().fromJson(result.get("result"), new TypeToken<List<Car>>() {
                                }.getType());
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        carAdapter.setList(cars);
                                    }
                                });

                            }
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {

                    }
                });
            }
        }).start();

    }


}